import common.TreeNode;

import java.util.*;

/**
 * @author tmh
 * @date 2024/10/6 20:27
 * @description
 */
public class T102二叉树的层序遍历 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root==null){
            return Collections.emptyList();
        }
        Deque<TreeNode> deque =  new ArrayDeque<>();
        List<List<Integer>> result = new ArrayList<>();
        deque.offer(root);
        while (!deque.isEmpty()){
            int len = deque.size();
            List<Integer> list = new ArrayList<>();
            while (len>0){
                TreeNode temp = deque.poll();
                list.add(temp.val);
                if (temp.left!=null){
                    deque.add(temp.left);
                }
                if (temp.right!=null){
                    deque.add(temp.right);
                }
                len--;
            }
            result.add(list);
        }
        return result;
    }
}
